package com.imgrate.migration.service;

import com.imgrate.migration.entity.Server;
import com.imgrate.migration.repository.ServerRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class ServerService {
    
    private final ServerRepository serverRepository;
    
    public Server createServer(Server server) {
        Server savedServer = serverRepository.save(server);
        log.info("创建服务器: {} ({})", server.getName(), server.getHostname());
        return savedServer;
    }
    
    public List<Server> getAllServers() {
        return serverRepository.findAll();
    }
    
    public Optional<Server> getServerById(Long id) {
        return serverRepository.findById(id);
    }
    
    public List<Server> getServersByOsType(String osType) {
        return serverRepository.findByOsType(osType);
    }
    
    public Server updateServer(Long id, Server serverDetails) {
        Optional<Server> serverOpt = serverRepository.findById(id);
        if (serverOpt.isPresent()) {
            Server server = serverOpt.get();
            server.setName(serverDetails.getName());
            server.setHostname(serverDetails.getHostname());
            server.setPort(serverDetails.getPort());
            server.setUsername(serverDetails.getUsername());
            server.setPassword(serverDetails.getPassword());
            server.setPrivateKey(serverDetails.getPrivateKey());
            server.setOsType(serverDetails.getOsType());
            server.setOsVersion(serverDetails.getOsVersion());
            server.setDescription(serverDetails.getDescription());
            
            Server updatedServer = serverRepository.save(server);
            log.info("更新服务器: {} ({})", server.getName(), server.getHostname());
            return updatedServer;
        }
        throw new RuntimeException("服务器不存在");
    }
    
    public void deleteServer(Long id) {
        serverRepository.deleteById(id);
        log.info("删除服务器ID: {}", id);
    }
}